import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
 Generated class for the HomeService provider.

 See https://angular.io/docs/ts/latest/guide/dependency-injection.html
 for more info on providers and Angular 2 DI.
 */
@Injectable()
export class HomeService {

  constructor(public http: Http) {
    console.log('Hello HomeService Provider');
  }

  get(URL) {
    return new Promise((resolve, reject) => {
      this.http.get(URL)
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        }, err => {
          reject(err);
        })
    })
  }

  //这种post方式在php中后台无法获取到数据，我们需要采用另外一种方式
  // post() {
  //   let header = new Headers();
  //   header.append('Content-Type', 'application/x-www-form-urlencoded');
  //   let pramas = JSON.stringify({ username: "", password: "" })
  //   return new Promise((resolve, reject) => {
  //     this.http.post(URL, pramas, header)
  //       .map(res => res.json())
  //       .subscribe(data => resolve(data), err => reject(err))
  //   })
  // }
  // //因为上面的请求参数在RequestPayload中，而下面的请求参数在formData中(具体可以看两者的区别)
  // post2() {
  //   let headers = new Headers({
  //     'Content-Type': 'application/x-www-form-urlencoded'
  //   });
  //   let options = new RequestOptions({
  //     headers: headers
  //   });
  //   let body= "username=admin&password=123456";
  //   return new Promise((resolve, reject) => {
  //     this.http.post(URL, body, options )
  //       .map(res => res.json())
  //       .subscribe(data => resolve(data), err => reject(err))
  //   })
  // }
}
